﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Common;
using Common.AI;

namespace CPI311
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Search : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;        // Drawing 2D stuff

        Camera camera;
        AStarSearch search;

        KeyboardState prevKeyboardState = Keyboard.GetState();
        MouseState prevMouseState = Mouse.GetState();

        List<Vector3> path;

        BasicEffect basicEffect;
        Random random;

        // some geometry
        Common.Plane plane;
        ModelObject cube;
        ModelObject player;
        ModelObject enemy;

        public Search()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            this.IsMouseVisible = true;
            random = new Random();
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();

        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            
            camera = new Camera();
            camera.Position = new Vector3(0, 60, 0);
            camera.Up = Vector3.UnitX;
            camera.LookAt = -Vector3.UnitY;
            camera.AspectRatio = GraphicsDevice.Viewport.AspectRatio;

            basicEffect = new BasicEffect(GraphicsDevice);

            plane = new Common.Plane();
            plane.Scale *= 50;

            cube = new ModelObject();
            cube.Model = Content.Load<Model>("Models/Cube");
            cube.Scale *= new Vector3(0.9f, 0.01f, 0.9f);

            player = new ModelObject();
            player.Model = Content.Load<Model>("Models/Sphere");

            enemy = new ModelObject();
            enemy.Model = player.Model;

            search = new AStarSearch(100, 100);
            for(int i = 0; i < 100; i++)
                for (int j = 0; j < 100; j++)
                {
                    search.Nodes[i, j].Position = new Vector3(-50 + i, 0, -50 + j);
                    search.Nodes[i, j].Row = i;
                    search.Nodes[i, j].Col = j;
                    search.Nodes[i, j].Passable = random.NextDouble() < 0.75f;
                }

            path = new List<Vector3>();
            MakeNewProblem();
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            KeyboardState keyboardState = Keyboard.GetState();
            MouseState mouseState = Mouse.GetState();

            if (keyboardState.IsKeyDown(Keys.Space) && prevKeyboardState.IsKeyUp(Keys.Space))
                MakeNewProblem();

            prevKeyboardState = keyboardState;
            prevMouseState = mouseState;

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            // Clear the screen
            GraphicsDevice.Clear(Color.Goldenrod);
            // Set the Depth Stencil State to default for 3D rendering

            basicEffect.View = camera.View;
            basicEffect.Projection = camera.Projection;

            basicEffect.DiffuseColor = new Vector3(0.5f, 0.5f, 0.5f);
            basicEffect.World = plane.World;
            plane.Draw(basicEffect);

            basicEffect.DiffuseColor = new Vector3(0.7f, 0.2f, 0.2f);
            foreach (AStarNode node in search.Nodes)
            {
                if (!node.Passable)
                {
                    cube.Position = node.Position;
                    basicEffect.World = cube.World;
                    cube.Draw(basicEffect);
                }
            }

            basicEffect.DiffuseColor = new Vector3(0.2f, 0.2f, 0.7f);
            basicEffect.World = player.World;
            player.Draw(basicEffect);

            basicEffect.DiffuseColor = new Vector3(0.2f, 0.7f, 0.2f);
            basicEffect.World = enemy.World;
            enemy.Draw(basicEffect);

            basicEffect.DiffuseColor = new Vector3(0.7f, 0.7f, 0.2f);
            lock (this)
            {
                foreach (Vector3 position in path)
                {
                    cube.Position = position;
                    basicEffect.World = cube.World;
                    cube.Draw(basicEffect);
                }
            }

            // Draw some string with rotation and scale
            spriteBatch.Begin();

            spriteBatch.End();
            base.Draw(gameTime);
        }

        private void FindPath(object obj)
        {
            search.Search();
            AStarNode node = search.End;
            lock (this)
            {
                path.Clear();
                while (node != null)
                {
                    path.Add(node.Position);
                    node = node.Parent;
                }
            }
        }

        private void MakeNewProblem()
        {
            do
            {
                int i = random.Next(100);
                int j = random.Next(100);
                if (search.Nodes[i, j].Passable)
                {
                    player.Position = search.Nodes[i, j].Position;
                    player.Position += Vector3.UnitY * 2;
                    search.End = search.Nodes[i, j];
                    break;
                }
            } while (true);

            do
            {
                int i = random.Next(100);
                int j = random.Next(100);
                if (search.Nodes[i, j].Passable)
                {
                    enemy.Position = search.Nodes[i, j].Position;
                    enemy.Position += Vector3.UnitY * 2;
                    search.Start = search.Nodes[i, j];
                    break;
                }
            } while (true);
            System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(FindPath));
        }
    
    }
}
